package com.leyou.goods.service;

import com.leyou.goods.client.BrandClient;
import com.leyou.goods.client.CategoryClient;
import com.leyou.goods.client.GoodsClient;
import com.leyou.goods.client.SpecificationClient;
import com.leyou.item.entity.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;


@Service
public class GoodsService {

    @Autowired
    private CategoryClient categoryClient;
    @Autowired
    private BrandClient brandClient;
    @Autowired
    private GoodsClient goodsClient;
    @Autowired
    private SpecificationClient specificationClient;


    @Autowired
    private AmqpTemplate amqpTemplate;

    private static final Logger LOGGER = LoggerFactory.getLogger(GoodsService.class);

    /**
     * 加载spu展示的数据
     * @param id
     * @return
     */
    public Map<String,Object> loadData(Long id){
       try {
           //用来存储返回的数据的
           Map<String,Object> model = new HashMap<>();
           //获取spu
           TbSpu spu = goodsClient.querySpuById(id);
           //获取spu的详细信息表
           TbSpuDetail spuDetail = goodsClient.querySpuDetailById(id);
           //初始化存储分类id和name的集合
           List<Map<String,Object>> categories = new ArrayList<>();
           //获取分类id集合
           List<Long> ids = Arrays.asList(spu.getCid1(), spu.getCid2(), spu.getCid3());
           //获取分类id对应的name
           List<String> names = categoryClient.queryCategoryNamesByCids(ids);
           //初始化存储分类id和name的集合  放在循环外面  避免多次创建
           for (int i = 0; i < ids.size(); i++) {
               Map<String,Object> map = new HashMap<>();
               map.put("id", ids.get(i));
               map.put("name", names.get(i));
               categories.add(map);
           }
           //获取skus集合
           List<TbSku> skus = goodsClient.querySkusBySpuId(id);
           //获取品牌对象
           TbBrand brand = brandClient.queryBrandById(spu.getBrandId());
           //获取分类下的所有分组以及分组下的规格参数信息
           List<TbSpecGroup> groups = specificationClient.querySepcGroupsWithParamsByCid(spu.getCid3());
           //获取分类下所有的特有规格参数信息
           List<TbSpecParam> params = specificationClient.queryParams(null, spu.getCid3(), null, false);

           //初始化存储规格参数id和name的map集合
           Map<Long,Object> paramMap=new HashMap<>();
           params.forEach(param -> {
               paramMap.put(param.getId(), param.getName());
           });
           model.put("categories", categories);
           model.put("brand", brand);
           model.put("spu", spu);
           model.put("spuDetail", spuDetail);
           model.put("skus", skus);
           model.put("groups", groups);
           model.put("paramMap", paramMap);
           return model;
       }catch (Exception e){
           LOGGER.error("加载商品数据出错了，spuId：{}{}",id,e);
       }
       return null;
    }




}
